/*
 * Copyright (c) 2010-2015. LiZaoNet Inc. (http://www.lizaonet.com).
 * license: http://www.lizaonet.com
 */

package com.spring;

import com.gradledemo.shiro.ShiroDbRealm;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by charles on 15-1-24.
 */
@Configurable
public class ShiroConfig {

    @Bean
    public ShiroDbRealm shiroDbRealm() {
        return new ShiroDbRealm();
    }

    @Bean
    @Qualifier("securityManager")
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(shiroDbRealm());
        securityManager.setCacheManager(shiroCacheManager());
        return securityManager;
    }

    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    public FormAuthenticationFilter authenticationFilter() {
        return new FormAuthenticationFilter();
    }

    @Bean
    public MemoryConstrainedCacheManager shiroCacheManager() {
        return new MemoryConstrainedCacheManager();
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilter() {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager());
        shiroFilter.setLoginUrl("login.htm");
        shiroFilter.setSuccessUrl("main.htm");
        shiroFilter.setUnauthorizedUrl("error.htm");

        Map<String, Filter> filters = new HashMap<>();
        filters.put("authc", authenticationFilter());
        shiroFilter.setFilters(filters);

        Map<String, String> definition = new HashMap<>();
        definition.put("/**.htm", "anon");
        definition.put("/admin/login.htm", "anon");
        definition.put("/admin/error.htm", "anon");
        definition.put("/admin/index.htm", "authc");
        shiroFilter.setFilterChainDefinitionMap(definition);
        return shiroFilter;
    }
}
